package com.sfac.springBoot.config;

import com.sfac.springBoot.interceptor.ViewMappingInterceptor;
import org.apache.catalina.TomcatPrincipal;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * personal demo
 **/
@Configuration
@AutoConfigureAfter(value = WebMvcAutoConfiguration.class)
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    ResourceConfig resourceConfig;
    @Autowired
    ViewMappingInterceptor viewMappingInterceptor;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("wind")){
            registry.addResourceHandler(resourceConfig.getResPathPattern())
                    .addResourceLocations(ResourceUtils.
                            FILE_URL_PREFIX+resourceConfig.getWindows());
        }else {
            registry.addResourceHandler(resourceConfig.getResPathPattern())
                    .addResourceLocations(ResourceUtils.
                            FILE_URL_PREFIX+resourceConfig.getLinux());
        }

    }

    @Bean
    public Connector connector(){
        Connector connector = new Connector();
        connector.setScheme("http");
        connector.setPort(80);
        return connector;
    }

    @Bean
    public ServletWebServerFactory servletWebServerFactory(){
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addAdditionalTomcatConnectors(connector());
        return factory;
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("POST","GET")
                .allowedOriginPatterns("*")
                .maxAge(3600);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(viewMappingInterceptor).addPathPatterns("/**");
    }
}
















